﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VINETLIFE.DO;
using VINETLIFE.BL;
using VINETLIFE.AdminCP;
using VINETLIFE.BaseClass;
using System.Data;

namespace VINETLIFE.Customers
{
    public partial class OrderHistory : System.Web.UI.Page
    {
        cmsOrdersDO objOrder = new cmsOrdersDO();
        cmsOrdersBL orderBL = new cmsOrdersBL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CustomerID"] != null)
            {
                if (!IsPostBack)
                {
                    grvOrdersDataSource();
                }
            }
            else
            {
                Functions.Alert("Bạn không có quyền truy cập vào khi chưa đăng nhập, vui lòng đăng nhập", "/dang-nhap/");
            }
        }
        protected void grvOrdersDataSource()
        {

            int customerId = int.Parse(Session["CustomerId"].ToString());
            string paymentMethod = "";
            string accountCode = "";
            string orderBy = "Id desc";
            string systemStatus = "";
            string orderTransactionStatus = "";
            string statusNotIn = "SystemStatus NOT IN ('ORDER_D')";

            string type = "";
            DateTime searchDate = new DateTime(1900, 1, 1);
            DateTime fromDate = new DateTime(1900, 1, 1);
            DateTime toDate = new DateTime(1900, 1, 1);

            if (rdSearchDate.Checked)
            {
                type = "date";
                if (txtSearchDate.Text != "")
                {
                    searchDate = Myfunction.ReturnValidateDateTime(txtSearchDate.Text.Trim());
                }
            }
            if (rdFromDate.Checked)
            {
                type = "fromdate";
                if (txtFromDate.Text != "")
                {
                    fromDate = Myfunction.ReturnValidateDateTime(txtFromDate.Text.Trim());
                }
                if (txtToDate.Text != "")
                {
                    toDate = Myfunction.ReturnValidateDateTime(txtToDate.Text.Trim());
                }
            }

            gridView.DataSource = new DataView(new cmsOrdersBL().SearchAdvanceHistory(customerId, paymentMethod, accountCode, orderBy, systemStatus, orderTransactionStatus, statusNotIn,type,searchDate,fromDate,toDate), statusNotIn, "", DataViewRowState.CurrentRows).ToTable();
            gridView.DataBind();
        }
        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            lbThongBao.Text = "";
            try
            {
                lbThongBao.Text = "";
                gridView.PageIndex = e.NewPageIndex;
                grvOrdersDataSource();
                details.Visible = false;
            }
            catch { }
        }
     
        public string TransactionOrderStatus(string Id)
        {
            string trangthai = "";
            objOrder.Id = int.Parse(Id);
            new cmsOrdersBL().Select(objOrder);
            if (objOrder.TransactionOrderStatus == "NEW")
            {
                trangthai = "Đơn hàng mới";
            }
            else if (objOrder.TransactionOrderStatus == "PROCESSING")
            {
                trangthai = "Đơn hàng đang xử lý";
            }
            else if (objOrder.TransactionOrderStatus == "COMPLETED")
            {
                trangthai = "Đơn hàng đã hoàn thiện";
            }
            else if (objOrder.TransactionOrderStatus == "WAITING")
            {
                trangthai = "Đơn hàng đang chờ xử lý";
            }
            else if (objOrder.TransactionOrderStatus == "CANCEL")
            {
                trangthai = "Đơn hàng đã hủy";
            }

            return trangthai;
        }
      
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
             DataRowView drview = e.Row.DataItem as DataRowView;
             if (e.Row.RowType == DataControlRowType.DataRow)
             {
                 Button btnCancelOrder = (Button)e.Row.FindControl("btnCancelOrder");
                 string orderTransactionStatus = EnumTransactionOrderStatus.V_ORDER_NEW;
                 try
                 {
                     orderTransactionStatus = drview["TransactionOrderStatus"].ToString();
                 }
                 catch { orderTransactionStatus = EnumTransactionOrderStatus.V_ORDER_NEW; }

                 if (orderTransactionStatus.Equals(EnumTransactionOrderStatus.V_ORDER_NEW))
                 {
                     btnCancelOrder.Enabled = true;
                 }
                 else
                 {
                     DisableButton(btnCancelOrder);
                     btnCancelOrder.Enabled = false;
                 }
             }

        }
        public void DisableButton(Button btn)
        {
            btn.Enabled = false;
            btn.Attributes.Add("onclick", "alert('Không thể thực hiện chức năng này cho đơn hàng này');");
            btn.CssClass = "disable-button button-gg-green";

        }
        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string commandName = e.CommandName.ToString().ToLower();
            int orderId = int.Parse(e.CommandArgument.ToString());
            int customerId = int.Parse(Session["CustomerId"].ToString());
            if (commandName.Equals("vieworder"))
            {
                
                details.Visible = true;
                LoadDetail(orderId);
                try
                {
                    cmsOrdersDO objOrder = orderBL.Select(new cmsOrdersDO { Id = orderId });
                    lblInvoiceNumber.Text = objOrder.InvoiceNumber;
                }
                catch { }
            }
            else if (commandName.Equals("cancelorder"))
            {
                try
                {
                    details.Visible = false;
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_CANCEL;
                    objOrder.LastModifiedId = -1;
                    objOrder.LastSaveDate = DateTime.Now;
                    objOrder.Note = "Khách hàng đã hủy đơn hàng này vào ngày: " + DateTime.Now.ToString("0:dd/MM/yyyy HH:mm tt");

                    orderBL.Update(objOrder);

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_CANCEL;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_CANCEL_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = -1;
                    objOrderHistory.Note = "Khách hàng đã hủy đơn hàng này vào ngày: " + DateTime.Now.ToString("0:dd/MM/yyyy HH:mm tt");
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    if (objOrder.IsUseVirtualAccount)
                    {
                        cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                        cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                        if (objAccountReceivedMoney != null)
                        {
                            if (objAccountReceivedMoney.ID > 0)
                            {
                                objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_CANCEL;
                                objAccountReceivedMoney.UserId = -1;
                                accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                            }
                        }

                        // Cap nhat lai tai khoan
                        cmsAccountDO objAccount = new cmsAccountDO();
                        cmsAccountBL accountBL = new cmsAccountBL();
                        cmsLogAccountDO objLogAccount = new cmsLogAccountDO();
                        cmsLogAccountBL logAccountBL = new cmsLogAccountBL();
                        accountBL.AccountInfoObject(objOrder.CustomerId);

                        if (objAccount != null)
                        {
                            if (objAccount.AccountId > 0)
                            {
                                objAccount.DepositBeforeTran = objAccount.Deposite;
                                objAccount.Deposite = objAccount.Deposite + objOrder.GrandTotal;
                                objAccount.LastSaveDate = DateTime.Now;
                                //  objAccount.LastModifiedId = -1;
                                accountBL.Update(objAccount);

                                // Ghi log tai khoan
                                objLogAccount.AccountId = objAccount.AccountId;
                                objLogAccount.Content = "Hoàn tiền vào tài khoản khi hủy đơn hàng: " + objOrder.InvoiceNumber;
                                objLogAccount.CreatedById = -1;
                                objLogAccount.CreatedDate = DateTime.Now;
                                objLogAccount.CurrentDeposite = objAccount.Deposite;
                                objLogAccount.DepositBeforeTran = objAccount.DepositBeforeTran;
                                objLogAccount.FromCustomerId = objOrder.CustomerId;
                                objLogAccount.OrderId = objOrder.Id;
                                objLogAccount.LogAccountPaymentCode = "CANCELORDER";
                                objLogAccount.LogAccountPayment = "Hoàn tiền khi hủy đơn hàng!";
                                objLogAccount.LogAccountType = "INCREASE";
                                logAccountBL.Insert(objLogAccount);
                            }
                        }
                    }
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "CancelhOrderScript", "<script type='text/javascript'>alert('Hủy đơn hàng thành công!')</script>", false);
                    grvOrdersDataSource();
                }
                catch
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "ErrorScript", "<script type='text/javascript'>alert('Có lỗi xảy ra!')</script>", false);
                }
            }
        }

        void LoadDetail(int OrderID)
        {
            listDetail.DataSource = new cmsOrderDetailsBL().GetByOrderId(OrderID);
            listDetail.DataBind();
        }

        protected void dropCountRow_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbThongBao.Text = "";
            gridView.PageSize = Convert.ToInt32(dropPageSize.SelectedValue);
            grvOrdersDataSource();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvOrdersDataSource();
        }
    }
}